package com.yuji.aacar.controller.order.pay;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseActivity;
import com.yuji.aacar.base.Const;
import com.yuji.aacar.controller.order.pay.bean.PayResult;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.tools.Tools;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.dialogue.CheckToast;
import com.yuji.aacar.widgets.dialogue.MyDialog;
import com.yuji.aacar.widgets.textview.PingFangTextView;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <li>Package:com.yuji.aacar.controller.order.pay</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/3/8</li>
 * <li>Description:   </li>
 */

public class PayActivity extends BaseActivity implements IWXAPIEventHandler {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.pay_number)
    PingFangTextView payNumber;
    @BindView(R.id.radioButton_weixin)
    RadioButton radioButtonWeixin;
    @BindView(R.id.radioButton_zhifubao)
    RadioButton radioButtonZhifubao;
    @BindView(R.id.pay_btn)
    Button payBtn;

    private static final int SDK_PAY_FLAG = 1;

    private String orderNum;
    private String amount;

    private int PayType = 1;//支付的类型 1：微信 2:支付宝
    private String actualIp;//用户终端IP 这里只是例子 接入时传真实的用户终端IP

    public static final int WEIXIN_CODE = 1;
    public static final int ALIPYA_CODE = 2;

    private IWXAPI api = null;
    private PayReq req;
//    private WeXinReceiver weXinReceiver;
    public static String WEIXIN_ACITON = "intent_action_pay_ok";
    public static String WEIXIN_ACITON_FAILED = "intent_action_pay_failed";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pay);
        ButterKnife.bind(this);
        initTitle(true, "订单支付", null);
        super.onCreate(savedInstanceState);
        orderNum = getIntent().getStringExtra("orderNumber");
        amount = getIntent().getStringExtra("amount");

        payNumber.setText("¥" + amount);
        payBtn.setText("微信支付¥" + amount);
        radioButtonZhifubao = (RadioButton) findViewById(R.id.radioButton_zhifubao);
        radioButtonWeixin = (RadioButton) findViewById(R.id.radioButton_weixin);
        radioButtonWeixin.setFocusable(true);
        radioButtonWeixin.setChecked(true);

//        actualIp = Tools.getHostIP();
        api = WXAPIFactory.createWXAPI(this, null);
        api.handleIntent(getIntent(), this);

        //        weXinReceiver = new WeXinReceiver();
        //        IntentFilter filter = new IntentFilter(WEIXIN_ACITON);
        //        registerReceiver(weXinReceiver, filter);

        radioButtonWeixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choosePayType(0);
            }
        });

        radioButtonZhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choosePayType(1);
            }
        });

    }

    @OnClick(R.id.pay_btn)
    public void onClick() {

        if (PayType == 1) {
            if (!api.isWXAppInstalled()) {
                CheckToast.showToast(this, "尚未安装微信", Toast.LENGTH_SHORT);
                //                showAlertDialogue();
            } else {
                if (null != orderNum) {
                    requestParams = BaseServiceParams.gen_alipay_paystr(orderNum);
                    doTask(BaseServiceMediator.WX_GEN);
                }


            }
        }
        if (PayType == 2) {
            //            PayManager aliPayManager = new AliPayManager(this);
            //            aliPayManager.excute(actualIp, ALIPYA_CODE, orderID, paymoney, auctionId, businessType);
            if (null != orderNum) {
                requestParams = BaseServiceParams.gen_alipay_paystr(orderNum);
                doTask(BaseServiceMediator.ALI_GEN);
            }

        }


        //        presentController(WaitForOrderConfirmActivity.class);
    }


    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.ALI_GEN_CODE) {
            String result = (String) response.getResponse();
            //            resetPriceUI(selectResponse);
            //            showToast(result);
            if (null != result) {
                showLoadingDialog();
                doAlipay(result);
            }
        } else if (response.getRequestCode() == BaseServiceMediator.WX_GEN_CODE) {
            String result = (String) response.getResponse();
            if (null != result) {
                showLoadingDialog();
                dopayWXPay(result);
            }
        }
    }

    @Override
    public void requestFailed(CoreServiceResponse response) {
        super.requestFailed(response);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        LogUtil.e("--onResp--","onReq");
        Toast.makeText(getApplicationContext(), "onReq", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResp(BaseResp baseResp) {
        int code = baseResp.errCode;
        LogUtil.e("--onResp--","onResp");
        if (code == 0) { //显示充值成功的页面和需要的操作
            showToast("支付成功！我们会尽快和您联系！");
            dismissLoadingDialog();
        } else if (code == -1) { //错误

        } else if (code == -2) { //用户取消

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

//    private class WeXinReceiver extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            dismissLoadingDialog();
//            if (intent.getAction().equals(WEIXIN_ACITON)) {
//                CommonDaoImpl.callBack.PaySuccess(UserBean.getInstance());
//                finish();
//            } else if (intent.getAction().equals(WEIXIN_ACITON_FAILED)) {
//                CheckToast.showToast(PayActivity.this, "微信支付失败", Toast.LENGTH_SHORT);
//            }
//        }
//    }


    /**
     * 选择支付方式;三者只能选择一种
     *
     * @param type 1，支付宝支付；0 微信支付
     */
    private void choosePayType(int type) {
        radioButtonWeixin.setChecked(false);
        radioButtonZhifubao.setChecked(false);
        switch (type) {
            case 0:
                radioButtonWeixin.setChecked(true);
                PayType = 1;
                payBtn.setText("微信支付¥" + amount);
                break;
            case 1:
                radioButtonZhifubao.setChecked(true);
                PayType = 2;
                payBtn.setText("支付宝支付¥" + amount);
                break;

            default:
                break;
        }

    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    dismissLoadingDialog();
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    LogUtil.e("--resultInfo--resultInfo--", resultInfo);
                    LogUtil.e("--resultInfo--resultStatus--", resultStatus);

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支付成功");
                        //                        CommonDaoImpl.callBack.PaySuccess(UserBean.getInstance());
                        //                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast("支付宝支付失败");
                        //                        CommonDaoImpl.callBack.PayFailed(resultStatus);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void doAlipay(final String orderBackInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderBackInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        //        Toast.makeText(mContext,orderInfo,Toast.LENGTH_SHORT).show();
    }


    protected void dopayWXPay(String result) {
        Map<String, String> Orderinfo = Tools.decodeXml(result);
        req = new PayReq();
        req.appId = Orderinfo.get("appid");
        req.partnerId = Orderinfo.get("partnerid");
        req.nonceStr = Orderinfo.get("noncestr");
        req.timeStamp = Orderinfo.get("timestamp");
        req.prepayId = Orderinfo.get("prepayid");
        req.packageValue = Orderinfo.get("package");
        req.sign = Orderinfo.get("sign");
        if (req.checkArgs()) {
            sendPayReq(req);
        }

        Toast.makeText(mContext, "weixin" + result, Toast.LENGTH_SHORT).show();
    }

    /**
     * 调起微信支付
     */
    private void sendPayReq(PayReq req) {
        api.registerApp(Const.WX_APP_ID);
        api.sendReq(req);
    }

    @Override
    public void onBackPressed() {
        MyDialog dialog = new MyDialog(this);
        dialog.createDialog("是否取消支付?", "确定", new MyDialog.MyOnclickListener() {
            @Override
            public void onClick(Dialog dialog) {
                finish();
            }
        });
    }
}
